package utils;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import exception.TokenException;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: lyy
 * Date: 2021/12/13 14:16
 */
public class JWTUtils {

	private static String key = "123";

	public static String createToken(Integer userId){
		Map<String, Object> payload = new HashMap<>();
		payload.put("userId", userId);
		payload.put("exp", Timestamp.valueOf(LocalDateTime.now().plusHours(1)));
		String token = JWTUtil.createToken(payload, key.getBytes());
		return token;
	}

	public static Integer parseToken(String token){
		boolean verify = verify(token);
		if(!verify){
			throw new TokenException("token 验证失败");
		}
		JWT jwt = JWTUtil.parseToken(token);
		Integer userId = (Integer) jwt.getPayload("userId");
		return userId;
	}

	public static boolean verify(String token){
		boolean verify = JWTUtil.verify(token, key.getBytes());
		return verify;
	}

}
